<?php

namespace app\user\service;

use think\facade\Config;
use think\facade\Log;
use EasyWeChat\OfficialAccount\Application;
use app\user\model\CommonUser;

/**
 * 微信服务类
 */
class WechatService
{
    /**
     * 微信应用实例
     */
    private $wxapp;

    public function __construct()
    {
        $this->wxapp = $this->createWechatApp();
    }

    /**
     * 获取用户信息
     *
     * @param string $openid
     * @return array|null
     */
    public function getUserInfo($openid)
    {
        try {
            $userInfo = $this->wxapp->getClient()->get('/cgi-bin/user/info', [
                'query' => [
                    'openid' => $openid,
                    'lang' => 'zh_CN'
                ]
            ])->toArray();

            return $userInfo;
        } catch (\Exception $e) {
            Log::error('获取微信用户信息失败: ' . $e->getMessage());
            return null;
        }
    }

    /**
     * 批量获取用户信息
     *
     * @param array $openids
     * @return array
     */
    public function batchGetUserInfo(array $openids)
    {
        try {
            $userList = $this->wxapp->getClient()->postJson('/cgi-bin/user/info/batchget', [
                'user_list' => array_map(function ($openid) {
                    return ['openid' => $openid, 'lang' => 'zh_CN'];
                }, $openids)
            ])->toArray();

            return $userList['user_info_list'] ?? [];
        } catch (\Exception $e) {
            Log::error('批量获取微信用户信息失败: ' . $e->getMessage());
            return [];
        }
    }

    /**
     * 发送模板消息
     *
     * @param string $openid
     * @param string $templateId
     * @param array $data
     * @param string $url
     * @return bool
     */
    public function sendTemplateMessage($openid, $templateId, $data, $url = '')
    {
        try {
            $result = $this->wxapp->getClient()->postJson('/cgi-bin/message/template/send', [
                'touser' => $openid,
                'template_id' => $templateId,
                'url' => $url,
                'data' => $data,
            ])->toArray();

            return $result['errcode'] === 0;
        } catch (\Exception $e) {
            Log::error('发送模板消息失败: ' . $e->getMessage());
            return false;
        }
    }

    /**
     * 创建菜单
     *
     * @param array $menu
     * @return bool
     */
    public function createMenu(array $menu)
    {
        try {
            $result = $this->wxapp->getClient()->postJson('/cgi-bin/menu/create', $menu)->toArray();

            return $result['errcode'] === 0;
        } catch (\Exception $e) {
            Log::error('创建菜单失败: ' . $e->getMessage());
            return false;
        }
    }

    /**
     * 获取AccessToken
     *
     * @return string|null
     */
    public function getAccessToken()
    {
        try {
            $accessToken = $this->wxapp->getAccessToken();
            return $accessToken->getToken();
        } catch (\Exception $e) {
            Log::error('获取AccessToken失败: ' . $e->getMessage());
            return null;
        }
    }

    /**
     * 验证请求来源
     * 在 EasyWeChat 6.x 中，签名验证通常在 handleMessage 中自动处理
     *
     * @return bool
     */
    public function validateRequest()
    {
        try {
            // EasyWeChat 6.x 在 serve() 方法中会自动验证签名
            // 这里可以添加额外的验证逻辑
            return true;
        } catch (\Exception $e) {
            Log::error('验证微信请求失败: ' . $e->getMessage());
            return false;
        }
    }

    /**
     * 处理微信消息
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function handleMessage()
    {
        $server = $this->wxapp->getServer();

        // 文本消息处理
        $server->with(function ($message, \Closure $next) {
            if ($message['MsgType'] === 'text') {
                return '收到文本消息：' . $message['Content'];
            }
            return $next($message);
        });

        // 事件消息处理
        $server->with(function ($message, \Closure $next) {
            if ($message['MsgType'] === 'event') {
                switch ($message['Event']) {
                    case 'subscribe':
                        return '欢迎关注！';
                    case 'unsubscribe':
                        // 取消关注逻辑
                        break;
                    case 'CLICK':
                        return '您点击了菜单：' . $message['EventKey'];
                }
            }
            return $next($message);
        });

        return $server->serve();
    }

    /**
     * 同步用户信息到数据库
     *
     * @param string $openid
     * @return array|null
     */
    public function syncUserToDatabase($openid)
    {
        $userInfo = $this->getUserInfo($openid);
        if (!$userInfo) {
            return null;
        }

        // 转换为用户对象格式
        $user = [
            'id' => $userInfo['openid'],
            'nickname' => $userInfo['nickname'],
            'avatar' => $userInfo['headimgurl'],
            'original' => $userInfo,
        ];

        return CommonUser::addWechatUser($user);
    }

    /**
     * 创建微信应用实例
     */
    private function createWechatApp()
    {
        $config = Config::get('wechat');

        return new Application([
            'app_id' => $config['app_id'],
            'secret' => $config['secret'],
            'token' => $config['token'],
            'aes_key' => $config['aes_key'],

            'log' => [
                'level' => $config['log']['level'] ?? 'info',
                'file' => $config['log']['file'] ?? runtime_path() . 'log/wechat.log',
            ],
        ]);
    }
}
